package service

import (
	"context"

	"gitee.com/WisdomClassroom/ClassStruct/glb"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gorm.io/gorm"
)

func (s *Service) ListClassStudents(ctx context.Context, request *pb.ListClassStudentsRequest) (*pb.ListClassStudentsResponse, error) {
	class := &models.ClassModel{UUID: request.GetClassUUID()}
	err := glb.DB.Preload("Students").Select("uuid").Take(class).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return &pb.ListClassStudentsResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "班级不存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return listClassStudentsRespSvrErr, nil
	}

	students := make([]*pb.StudentBasicInfo, 0, len(class.Students))
	for _, student := range class.Students {
		students = append(students, &pb.StudentBasicInfo{
			AccountID: student.AccountID,
			Name:      student.Name.String,
			Gender:    student.Gender.Int32,
		})
	}

	return &pb.ListClassStudentsResponse{
		Status:   &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
		Students: students,
	}, nil
}
